package pay.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pay.commont.CouponStatus;
import pay.commont.SettingDictType;
import pay.dao.CouponAppUserDao;
import pay.service.CouponAppUserService;
import pay.dao.SettingDictMapper;
import pay.entity.CouponAppUserEntity;
import pay.entity.SettingDict;
import pay.utils.DateUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service
public class CouponAppUserServiceImpl extends ServiceImpl<CouponAppUserDao, CouponAppUserEntity> implements CouponAppUserService {

    @Resource
    private SettingDictMapper settingDictMapper;

    @Resource
    private CouponAppUserDao couponAppUserDao;

    @Override
    @Transactional
    public void grantVipCoupon(String userId) {
        SettingDict settingDict = settingDictMapper.selectOne(new QueryWrapper<SettingDict>().eq("`key`", SettingDictType.VIP_COUPON_ID_LIST.getValue()));

        if (settingDict == null || settingDict.getValue() == null) {
            return;
        }
        List<Integer> couponIdList = Arrays.stream(settingDict.getValue().split(","))
                .map(String::trim)         // 去除空格，防止 " 123 "
                .filter(s -> !s.isEmpty()) // 防止空字符串报错
                .map(Integer::valueOf)     // 转换为 Integer
                .collect(Collectors.toList());
        couponIdList.forEach(couponId -> {
            List<CouponAppUserEntity> couponAppUserEntityList = couponAppUserDao.selectCouponAppUserByUserIdAndCouponId(userId, couponId);
            AtomicReference<Boolean> flag = new AtomicReference<>(true);
            couponAppUserEntityList.forEach(couponAppUser -> {
                if (!DateUtils.compareDateNow(couponAppUser.getEndTime())) {
                    flag.set(false);
                }
            });
            if (flag.get()) {
                // 如果本月没有优惠券
                CouponAppUserEntity couponAppUserEntity = new CouponAppUserEntity();
                couponAppUserEntity.setUserId(userId);
                couponAppUserEntity.setCouponId(couponId);
                couponAppUserEntity.setCouponCode(UUID.randomUUID().toString());
                couponAppUserEntity.setStartTime(new Date());
                couponAppUserEntity.setEndTime(DateUtils.getMonthEndTimeJoda());
                couponAppUserEntity.setStatus(CouponStatus.NO_USE.getStatus());
                couponAppUserEntity.setSource(2);
                Integer status = couponAppUserDao.insert(couponAppUserEntity);
                if (status <= 0) {
                    throw new RuntimeException("服务器错误");
                }
            }
        });
    }

}




